package com.xs.ahoi.hcxs.tencent;

import android.content.ComponentName;
import android.content.Intent;
import android.support.v4.app.Fragment;
import com.tencent.connect.UserInfo;
import com.tencent.connect.auth.QQToken;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.xs.ahoi.hcxs.Ahoi;
import com.xs.ahoi.hcxs.dao.AppUserInfo;
import com.xs.ahoi.hcxs.utils.FileUtil;
import com.xs.ahoi.hcxs.utils.LogUtil;
import com.xs.ahoi.hcxs.utils.ToastUtil;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * author: ahoi
 * date: 2018/8/16 13:44
 * description: QQ登录 分享功能
 */
public class QQManager {

    private static final String APPID = "1106987207";

    private static QQManager instance;
    private QQIUiListener mIUiListener;
    private LoginCallback loginCallback;
    private Tencent mTencent;
    private AppUserInfo appUserInfo;

    private QQManager() {
        initTencent();
        mIUiListener = new QQIUiListener();
    }

    public static QQManager getInstance() {
        if (instance == null) {
            instance = new QQManager();
        }
        return instance;
    }

    // 初始化Tencent对象
    private void initTencent() {
        if (mTencent == null) {
            mTencent = Tencent.createInstance(APPID, Ahoi.getInstance().getApplicationContext());
        }
    }

    // 防止重复登录
    public void login(Fragment fragment) {
        if (!mTencent.isSessionValid()) {
            loginCallback.showL("跳转登录");
            mTencent.login(fragment, "all", mIUiListener);
        }
    }

    // 退出登录
    public void loginOut(Fragment fragment) {
        if (mTencent.isSessionValid()) {
            mTencent.logout(fragment.getContext());
            appUserInfo = null;
        }
    }

    // 分享文件
    public static Intent shareFile(String filePath) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        ComponentName component = new ComponentName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.JumpActivity");
        intent.setComponent(component);
        intent.putExtra(Intent.EXTRA_STREAM, FileUtil.getFileUri(filePath));
        intent.setType("text/plain");
        return Intent.createChooser(intent, "startActivity to...");
    }

    // 分享文本
    public static Intent shareText(String text) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        ComponentName component = new ComponentName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.JumpActivity");
        intent.setComponent(component);
        intent.putExtra(Intent.EXTRA_TEXT, text);
        intent.setType("text/plain");
        return Intent.createChooser(intent, "startActivity to...");
    }

    // 将登录后的信息转化为系统用户对象
    private void parseObjectToUser(Object obj) {
        try {
            JSONObject jb = (JSONObject) obj;
            LogUtil.e("QQManager userInfo: " + jb.toString());
            if (appUserInfo == null) {
                appUserInfo = new AppUserInfo();
            }
            appUserInfo.setOpenId(mTencent.getOpenId());
            appUserInfo.setCity(jb.getString("city"));
            appUserInfo.setProvince(jb.getString("province"));
            appUserInfo.setGender(jb.getString("gender"));
            appUserInfo.setYear(jb.getInt("year"));
            appUserInfo.setNickName(jb.getString("nickname"));
            appUserInfo.setFigureUrl(jb.getString("figureurl_qq_2"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Tencent.onActivityResultData(requestCode, resultCode, data, mIUiListener);
        if (requestCode == Constants.REQUEST_API) {
            if (resultCode == Constants.REQUEST_QQ_SHARE || resultCode == Constants.REQUEST_OLD_SHARE) {
                Tencent.handleResultData(data, mIUiListener);
            }
        }
    }

    // 实现登录成功与否的接口
    private class QQIUiListener implements IUiListener {

        @Override
        public void onComplete(Object object) { // 登录成功
            loginCallback.showL("提取用户");
            // 获取openid和token
            getOpenIdAndToken(object);

            // 获取用户信息
            getUserInfo();
        }

        @Override
        public void onError(UiError uiError) {  // 登录失败
            ToastUtil.show("登录失败");
            loginCallback.hideL();
        }

        @Override
        public void onCancel() {                // 取消登录
            ToastUtil.show("用户取消登录");
            loginCallback.hideL();
        }
    }

    // 获取openid和token
    private void getOpenIdAndToken(Object object) {
        JSONObject jb = (JSONObject) object;
        try {
            // openid用户唯一标识
            String openID = jb.getString("openid");
            String access_token = jb.getString("access_token");
            String expires = jb.getString("expires_in");

            mTencent.setOpenId(openID);
            mTencent.setAccessToken(access_token, expires);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    // 获取用户信息
    private void getUserInfo() {
        QQToken token = mTencent.getQQToken();
        new UserInfo(Ahoi.getInstance().getApplicationContext(), token).getUserInfo(new IUiListener() {
            @Override
            public void onComplete(Object object) {
                parseObjectToUser(object);
                loginCallback.updateV();
                loginCallback.hideL();
            }

            @Override
            public void onError(UiError uiError) {
                loginCallback.hideL();
            }

            @Override
            public void onCancel() {
                loginCallback.hideL();
            }
        });
    }

    public AppUserInfo getUser() {
        return appUserInfo;
    }

    public QQManager setLoginCallback(LoginCallback loginCallback) {
        this.loginCallback = loginCallback;
        return this;
    }

    public interface LoginCallback {
        void showL(String msg);

        void hideL();

        void updateV();
    }

}
